
import { ref, reactive, onMounted, onUnmounted, provide, } from 'vue';
import type { FormInstance} from "element-plus";
import { getLabelList,postLabelList } from "@/api/modules/goodsArchive/list/information.ts";
import { ResultEnum } from "@/enums/httpEnum";
import applicationLabelComponent from './index.vue';
import { failMsg, successMsg } from "@/utils/messageUtils";
import I18n from "@/languages/index";
const $t = I18n.global.t;
interface Ioptions {
    labe: string, value: string | number
}
interface IformDataItem {
    label: string,
    name: string,
    prop_id: string | number,
    value: string | number,
    options?: Ioptions[],
    attr?: object,
    type: string,
    placeholder: string
}

const businessType = 1; //1 qifa销售，2清关
const msg = reactive<Object>({
    title: 'goods_information_consumer.application_label',
    content: '内容',
    tabTileBase: 'goods_archive.edit_base_info',
    tabTileSaleProps: 'goods_archive.sales_attr',
    tabTileCustomsClearanceProps: 'goods_archive.customs_clearance_attr',
    tabTileGoodsBarCode: 'goods_archive.goods_barcode',
    noModifications:"goods_archive.no_modifications",
    save:"merak.save",
    cancel:"merak.cancel"
})




/**
 * 使用编辑企发属性表单的钩子函数。
 * 
 * @param proxy - 代理对象，用于访问全局属性和方法。
 * @returns 返回一个对象，包含 组件和显示编辑器属性的函数。
 */
const goodsApplicationLabelProps = (proxy): Object => {
	//获取当天日期
	const currentDate = ()=>{
		const date = new Date();
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		const day = date.getDate();
		return `${year}-${month<=9?'0'+month:month}-${day<=9?'0'+day:day}`
	}
    // 参考编辑表单的可见性状态。
    const applicationLabelVisible = ref<boolean>(false);
    const applicationLabelFromData = ref<any>({
		"quantity":"",   //申请数量  必填
		"release_method_type":"",   //申请类别  1进口 2本地  必填
		"deliver_date":currentDate(),   //交付日期   必填
		"production_date":"",  //生产日期  必填
		"apply_order_type":"",   //申请单类型  0分段 1整箱  必填
		"num_in_container":"",   //运输包装内SSCC(KM)数量   不必填
		"import_company_id":"",  //进口公司id  批量操作时不需要传值  不必填
		"express_pdf":"",//唛头凭证
	});
	let pIdArr = ref([]);
    let queue = [];
	
	
	//页面的select下拉数据
	const applicationLabelOptions = reactive({
		applicationType: [],//申请类别
		distributionType: [],//分配形式
		manufacturerType: [],//厂家名称
		expressPdfType:[],//唛头凭证
	})
	const getLabelFun = (isArr,pid) => {
		let dataMsg = {};
		if(isArr){
			
		} else {
			dataMsg.product_id=pid[0]
		}
		getLabelList(dataMsg).then(({ code, data }) => {
			if (code == ResultEnum.SUCCESS) {
				applicationLabelOptions.applicationType = data.release_method_type;
				applicationLabelOptions.distributionType = data.distribution_form;
				applicationLabelOptions.manufacturerType = data.factory_list;
				applicationLabelOptions.expressPdfType = data.express_pdf;
				applicationLabelFromData.value.express_pdf = 0;
			}
		});
	};
	const applicationLabelNewRules = reactive<FormRules<RuleForm>>({})
	const validateInput = (rule, value, callback) => {
	  if (Number(value) > 3000) {
	    return callback(new Error($t('goods_information_consumer.error_num')));
	  }
	  callback();
	};
	const applicationLabelRules = reactive<FormRules<RuleForm>>({
		quantity: [
			{
				required: true,
				message: $t('goods_information_consumer.error_max_num'),
				trigger: 'change',
			},
			{
				validator: validateInput, 
				trigger: 'change' ,
			},
		],
		release_method_type: [
			{
				required: true,
				message: $t('goods_information_consumer.error_release_method_type'),
				trigger: 'blur',
			},
		],
		deliver_date: [
			{
				required: true,
				message: $t('goods_information_consumer.error_deliver_date'),
			},
		],
		production_date: [
			{
				required: true,
				message: $t('goods_information_consumer.error_production_date'),
			},
		],
		apply_order_type: [
			{
				required: true,
				message: $t('goods_information_consumer.error_apply_order_type'),
				trigger: 'blur',
			},
		],
		express_pdf: [
			{
				required: true,
				message: $t('goods_information_consumer.error_express_pdf'),
				trigger: 'blur',
			},
		],
	})
    /**
     * 显示编辑表单的功能。
     *  
     */
    const applicationLabelShowFn = (msgdata:any,isArr) => {
		getLabelFun(isArr,msgdata)
		pIdArr.value = msgdata;
        applicationLabelVisible.value = true;

    }
    const applicationLabelResetFn = () => {
        Object.keys(applicationLabelFromData.value).map(key => {
            applicationLabelFromData.value[key] = ''
        });
        applicationLabelVisible.value = false;
    }
    const applicationLabelSavetFn =  async (formEl : FormInstance | undefined) => {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				let postData = {};
				console.log(applicationLabelFromData)
				if(applicationLabelFromData.num_in_container != ''){
					//console.log(Number(applicationLabelFromData.value.quantity))
					//console.log(Number(applicationLabelFromData.value.num_in_container))
					//console.log(Number(applicationLabelFromData.value.quantity) % Number(applicationLabelFromData.value.num_in_container))
					if(Number(applicationLabelFromData.value.quantity) % Number(applicationLabelFromData.value.num_in_container) > 0){
						applicationLabelNewRules.num_in_container = $t('goods_information_consumer.error_count')
						return false;
					}
				}
				postData.product_ids = pIdArr.value;
				postData.data = applicationLabelFromData.value;
				postData.data.source = 2;
				postLabelList(postData).then(({ code, data, message,errors }) => {
					if (code == 2000) {
						successMsg($t('goods_information_consumer.success_tag'));
						applicationLabelResetFn();
					} else {
						failMsg(message)
						// if(Object.keys(errors).length !== 0){
						// 	Object.assign(newRules,errors);
						// } else {
						// 	failMsg(message)
						// }
					}
				})
			} else {
				console.log('error submit!', fields)
			}
		})
  //       let formData = {};
  //       Object.keys(applicationLabelFromData.value).map(key => {
  //           formData[key] = applicationLabelFromData.value[key];
  //       });
		// console.log(formData)
  //       applicationLabelResetFn();
        //applicationLabelOptions.saveCallback({ queue, props:formData,type:businessType })
    }


    // 本地化消息文本。
    const lang = () => {
        Object.keys(msg).map(key => {
            // 将消息文本的关键字替换为相应的本地化版本。
            msg[key] = proxy.$t(msg[key])
        })
    }
    lang(); // 初始化时执行本地化。

    // 提供依赖 
    provide('applicationLabelVisible', applicationLabelVisible);
    provide('applicationLabelMsg', msg);
    provide('applicationLabelFromData', applicationLabelFromData);
	 provide('applicationLabelOptions', applicationLabelOptions);
    provide('applicationLabelResetFn', applicationLabelResetFn);
    provide('applicationLabelSavetFn', applicationLabelSavetFn);
	provide('applicationLabelRules', applicationLabelRules);
	provide('applicationLabelNewRules', applicationLabelNewRules);
	
    // 返回编辑器组件和控制显示的函数。
    return {
        applicationLabelComponent,
		applicationLabelSavetFn,
		applicationLabelShowFn,
    }
}

export default goodsApplicationLabelProps



